package com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bes.sdk.utils.SettingsJsonUtils;
import com.google.android.material.tabs.TabLayout;
import com.mylhyl.circledialog.CircleDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.sport.DevicePanelSettingTabAdapter;
import bb.lanxing.lib.devices.sgsettingentity.setting.PanelDisplayData;
import bb.lanxing.lib.devices.sgsettingentity.setting.PanelModel;
import bb.lanxing.model.sport.SportTypeGroup;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.ui.GsonUtils;
import bb.lanxing.utils.PanelModelToJsonUtil;

public class DevicePanelSettingActivity extends BaseActivity {
    public final SportTypeGroup[] CATEGORY = {
            new SportTypeGroup(R.string.sport_item_category_distance, new int[]{101}),
            new SportTypeGroup(R.string.sport_item_category_speed, new int[]{201, 202, 203, 204, 205, 206, 207}),
            new SportTypeGroup(R.string.sport_item_category_time, new int[]{301, 302, 303}),
            new SportTypeGroup(R.string.sport_item_category_altitude, new int[]{401, 402, 403}),
            new SportTypeGroup(R.string.sport_item_category_gradient, new int[]{501, 502, 503}),
            new SportTypeGroup(R.string.sport_item_category_generic, new int[]{601}),
            new SportTypeGroup(R.string.sport_item_category_heart, new int[]{701, 702, 703}),
            new SportTypeGroup(R.string.sport_item_category_cadence, new int[]{801, 802, 803}),
            new SportTypeGroup(R.string.sport_item_category_power, new int[]{901, 903, 905, 906, 907}),
            new SportTypeGroup(R.string.sport_item_category_direction, new int[]{1002}),
            new SportTypeGroup(R.string.sport_item_category_temperature, new int[]{1101, 1102, 1103})};

    private DevicePanelSettingAdapter mDevicePanelSettingAdapter;

    private LinearLayout tabPage;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public DevicePanelSettingTabAdapter mPanelSettingTabAdapter;

    private List<Integer> mPanelItemTypeList;
    private int mItemPosition = 0;

    /**
     * 下方默认选择哪一页
     */
    private int mSelectedTab = -1;
    private int mSelectedItem = -1;
    private boolean isSaved = false;

    private PanelModel PANEL_MODEL;
    private int sportMode;
    private int pageIndex;
    private int panelId;
    private List<Integer> panelItems;
    private String device_model = "BC270";
    private String sn = "test";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_panel_setting);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());

        TextView save = findViewById(R.id.save);
        save.setOnClickListener(v -> saveContentToFile());

        PANEL_MODEL = GsonUtils.Companion.getInstance().fromJson(getIntent().getStringExtra("PANEL_MODEL"), PanelModel.class);
        sportMode = getIntent().getIntExtra("sportMode", 0);
        pageIndex = getIntent().getIntExtra("pageIndex", 0);
        panelId = getIntent().getIntExtra("panelId", 0);
        int panelIdOld = getIntent().getIntExtra("panelIdOld", 0);
        if (panelIdOld != panelId || PANEL_MODEL == null) {
            switch (panelId) {
                case 1:
                    panelItems = Arrays.asList(901, 0, 0, 0, 0, 0, 0, 0);
                    break;
                case 2:
                    panelItems = Arrays.asList(901, 101, 0, 0, 0, 0, 0, 0);
                    break;
                case 3:
                    panelItems = Arrays.asList(901, 101, 302, 0, 0, 0, 0, 0);
                    break;
                case 4:
                    panelItems = Arrays.asList(901, 101, 302, 301, 0, 0, 0, 0);
                    break;
                case 5:
                    panelItems = Arrays.asList(901, 101, 302, 301, 201, 0, 0, 0);
                    break;
                case 6:
                    panelItems = Arrays.asList(901, 101, 301, 205, 201, 203, 0, 0);
                    break;
                case 7:
                    panelItems = Arrays.asList(901, 101, 401, 301, 205, 201, 203, 0);
                    break;
                case 8:
                    panelItems = Arrays.asList(901, 302, 101, 401, 301, 205, 201, 203);
                    break;
            }
        } else {
            panelItems = PANEL_MODEL.getProfilesList().get(sportMode).getDisplayData().get(pageIndex).getItems();
        }
        mPanelItemTypeList = new ArrayList<>();
        for (int i = 0; i < panelItems.size(); i++) {
            if (panelItems.get(i) != 0) {
                mPanelItemTypeList.add(panelItems.get(i));
            } else {
                break;
            }
        }

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position < 8 - panelId) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        mDevicePanelSettingAdapter = new DevicePanelSettingAdapter(mPanelItemTypeList);
        mDevicePanelSettingAdapter.setOnItemClickListener(position -> {
            mDevicePanelSettingAdapter.setIdSelected(position);
            mItemPosition = position;
            setSelectedItem(mPanelItemTypeList.get(position));
        });
        recyclerView.setAdapter(mDevicePanelSettingAdapter);

        tabPage = findViewById(R.id.tabPage);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.pager);

        mPanelSettingTabAdapter = new DevicePanelSettingTabAdapter(CATEGORY, getSupportFragmentManager());
        viewPager.setAdapter(mPanelSettingTabAdapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mPanelSettingTabAdapter.updateSelectedTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    public void setSportItem(int sportItemType) {
        mPanelItemTypeList.set(mItemPosition, sportItemType);
        panelItems.set(mItemPosition, sportItemType);
        mDevicePanelSettingAdapter.setPanelItemTypeList(mPanelItemTypeList);
        isSaved = false;
    }

    private void setSelectedItem(int sportItemType) {
        for (int i = 0; i < CATEGORY.length; i++) {
            for (int j = 0; j < CATEGORY[i].getTypes().length; j++) {
                if (sportItemType == CATEGORY[i].getTypes()[j]) {
                    mSelectedTab = i;
                    mSelectedItem = j;
                    break;
                }
            }
        }
        if (mSelectedTab < 0) {
            return;
        }
        tabLayout.getTabAt(mSelectedTab).select();
        mPanelSettingTabAdapter.mPanelSettingTypeFragments.get(mSelectedTab).getDevicePanelSettingTypeAdapter()
                .updateSelectedItem(mSelectedTab, mSelectedItem);
        mPanelSettingTabAdapter.removeUnselectedItem();
        tabPage.setVisibility(View.VISIBLE);
        viewPager.setVisibility(View.VISIBLE);
    }

    private void saveContentToFile() {
        if (PANEL_MODEL != null) {
            PanelDisplayData panelDisplayData = PANEL_MODEL.getProfilesList().get(sportMode).getDisplayData().get(pageIndex);
            panelDisplayData.setPanelId(panelId);
            panelDisplayData.setItems(panelItems);
        }
        String content = PanelModelToJsonUtil.toJson(PANEL_MODEL);
        device_model = SettingsJsonUtils.getDeviceModel(this);
        sn = SettingsJsonUtils.getSn(this);
        CommonUtil.saveDeviceProfile(content, device_model, sn);
        CommonUtil.sendPanelsJsonFile(context, device_model, sn);
        toast(getString(R.string.toast_save_successful));
        isSaved = true;
    }

    private void save() {
        saveContentToFile();
        Intent intent = new Intent();
        intent.putExtra("PANEL_MODEL", PanelModelToJsonUtil.toJson(PANEL_MODEL));
        intent.putExtra("panelId", panelId);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (isSaved) {
            save();
        } else {
            new CircleDialog.Builder().setTitle(getString(R.string.save)).setText(getString(R.string.save_current_settings))
                    .setPositive(getString(R.string.save), v -> {
                        save();
                        return true;
                    }).setNegative(getString(R.string.cancel), v -> {
                        super.onBackPressed();
                        return true;
                    }).show(getSupportFragmentManager());
        }
    }
}